from flask import Blueprint, render_template
from flask_login import login_required
from app.models import MonitorPoint, MonitorData, User, AlarmRecord
from datetime import datetime, timedelta
from sqlalchemy import desc

bp = Blueprint('main', __name__)

@bp.route('/')
@login_required
def index():
    now = datetime.utcnow()
    today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
    
    # 获取统计数据
    stats = {
        'points_count': MonitorPoint.query.count(),
        'today_data_count': MonitorData.query.filter(MonitorData.timestamp >= today_start).count(),
        'active_alarms': AlarmRecord.query.filter_by(status='active').count(),
        'user_count': User.query.filter_by(status='active').count()
    }
    
    # 获取所有监控点及其最新数据
    points = MonitorPoint.query.all()
    for point in points:
        point.latest_data = MonitorData.query.filter_by(point_id=point.id)\
            .order_by(desc(MonitorData.timestamp)).first()
    
    # 获取最新的5条报警信息
    alarms = AlarmRecord.query.filter_by(status='active')\
        .order_by(desc(AlarmRecord.created_at)).limit(5).all()
    
    return render_template('index.html',
                         stats=stats,
                         points=points,
                         alarms=alarms,
                         now=now) 